import { AnyAction } from "redux";
import * as TYPES from "../action-types";
import Dog from "@/typings/dog";

export interface CartItem {
  name: string;
  dog: Dog;
  count: number;
  checked: boolean;
  CartState: [];
}

type CartState = CartItem[];

let initialState: CartState = [];

const reducer = function (state: CartState = initialState, action: AnyAction) {
  switch (action.type) {
    case TYPES.ADD_CART_ITEM:
      let oldIndex = state.findIndex(
        (item) => item.dog.id === action.payload.id
      );
      if(oldIndex==-1){
          return[
              ...state,
              {
                  checked:false,
                  count:1,
                  dog:action.payload,
              }
          ];
      }else{
          let item=state[oldIndex];
          return [
              ...state.slice(0,oldIndex),
              {
                  ...item,
                  count:item.count+1

              },
              ...state.slice(oldIndex+1)
          ]
      }
     case TYPES.REMOVE_CART_ITEM:
         let removeIndex=state.findIndex(
             (item)=>item.dog.id===action.payload
         ); 
         return [...state.slice(0,removeIndex),...state.slice(removeIndex+1)]
    case TYPES.CLEAR_CART_ITEMS:
        return [];
    case TYPES.CHANGE_CAR_ITEM_COUNT:
        return state.map(
            (item)=>{
                if(item.dog.id===action.payload.id){
                    item.count=action.payload.count;
                }
                return item;                
            }
        );  
    case TYPES.CHANGE_CHECKED_CART_ITEMS:
        let checkIds=action.payload;
        return state.map((item)=>{
            if(checkIds.includes(item.dog.id)){
                item.checked=true;
            }else{
                item.checked=false;
            }
            return item;
        })  
    case TYPES.SETTLE:
        return state.filter((item)=>!item.checked)       
         default:
      return state;
  }
};
export default reducer;
